import re

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }
#自定义返回后端第一种
from django.contrib.auth.backends import ModelBackend

class UsernameMobileModelBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
    #     try:
    #         if re.match(r'1[345789]\d{9}',username):
    #             user = User.objects.get(mobile=username)
    #         else:
    #             user = User.objects.get(username=username)
    #     except User.DoesNotExist:
    #         return None

        user = get_users(username)
        if user.check_password(password):
            return user





#代码抽取
def get_users(username):
    try:
        if re.match(r'1[345789]\d{9}', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    else:
        return user

#自定义返回后端第二种
class SettingsBackend(object):
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """

    def authenticate(self, request, username=None, password=None):
        # try:
        #     if re.match(r'1[345789]\d{9}',username):
        #         user = User.objects.get(mobile=username)
        #     else:
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return None
        user = get_users(username)

        if user.check_password(password):
            return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


